package com.cardbaobao.cardbabyclient.service;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.IBinder;
import android.os.Process;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.NotificationCompat;

import com.cardbaobao.cardbabyclient.R;
import com.cardbaobao.cardbabyclient.utils.SharedPreferencesUtil;
import com.cardbaobao.cardbabyclient.utils.ToastUtil;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Locale;

/**
 * Created by Jiangzx on 2017/7/31 10:05.
 */

public class AppUpdateService extends Service {
    private static final int MAX_RE_TYR_COUNT =3;
    private static final String DIR="cardbaobao";

    private static final String APK_NAME="cbbLatest.apk";

    private static final String SD_CARD_DISABLE="存储卡不可用";

    private static final String CREATE_FILE_FAILURE="创建文件失败";

    private int fileStartByte;

    private Handler handler;

    private int reTryCount;
    @Override
    public int onStartCommand(Intent intent,int flags, int startId) {
        if(intent!=null){
            if(Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())){
                File root=Environment.getExternalStorageDirectory();
                if(root==null){
                    ToastUtil.showToastLongOnScreenCenter(SD_CARD_DISABLE);
                }else {
                    String dirName=root.getAbsolutePath()+File.separator+DIR;
                    File dir=new File(dirName);
                    boolean dirExist=true;
                    if(!dir.exists()){
                        dirExist=dir.mkdirs();
                    }
                    if(dirExist){
                        //文件夹创建成功
                        String fileName=dirName+File.separator+APK_NAME;
                        File file=new File(fileName);
                        boolean deleteSuc=true;
                        if(file.exists()){
                            deleteSuc=file.delete();
                        }
                        boolean createSuc=true;
                        if(deleteSuc){
                            try {
                                createSuc=file.createNewFile();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                        if(createSuc){
                            //开始下载
                            handler=new Handler();
                            startDownLoadApkFile(SharedPreferencesUtil.CbbInfo.getAppLatestApkUrl(),
                                    fileName);
                        }
                    }else{
                        ToastUtil.showToastLongOnScreenCenter(CREATE_FILE_FAILURE);
                    }
                }
            }else{
                ToastUtil.showToastLongOnScreenCenter(SD_CARD_DISABLE);
            }
        }
        return super.onStartCommand(intent, flags, startId);
    }

    //开始下载apk安装文件
    private void startDownLoadApkFile(@NonNull final String apkUrl, @NonNull final String fileName){
        new Thread(new Runnable() {
            @Override
            public void run() {
                RandomAccessFile file=null;
                HttpURLConnection connection=null;
                InputStream in=null;
                try {
                    file=new RandomAccessFile(fileName,"rw");
                    URL url=new URL(apkUrl);
                    connection= (HttpURLConnection) url.openConnection();
                    connection.setUseCaches(false);
                    connection.setReadTimeout(30000);
                    connection.setConnectTimeout(45000);
                    connection.setRequestMethod("GET");
                    connection.setRequestProperty("Range","bytes="+ fileStartByte +"-");
                    connection.connect();
                    int responseCode=connection.getResponseCode();
                    if(responseCode==HttpURLConnection.HTTP_PARTIAL){
                        in=connection.getInputStream();
                        int total=connection.getContentLength();
                        String totalM=String.format(Locale.CHINESE,"%.2f",total/1024/1024f);
                        showNotification("安装文件共"+totalM+"M，已下载1M",1);
                        file.setLength(total);
                        byte[] bytes=new byte[4*1024];//4k
                        int length=in.read(bytes);
                        int writes=0;
                        while(length>0){
                            file.seek(fileStartByte);
                            file.write(bytes,0,length);
                            fileStartByte+=length;
                            writes+=length;
                            //计算百分比，每下载1%发次通知
                            if(writes>=total/100){
                                writes=0;
                                long downloadBytes=file.getFilePointer();
                                String downloadM=String.format(Locale.CHINESE,"%.2f",downloadBytes/1024/1024f);
                                int percent= (int) ((float)downloadBytes/total*100);
                                showNotification("安装文件共"+totalM+"M，已下载"+downloadM+"M",percent);
                            }else{
                                if(fileStartByte==total){
                                    //已下载完成
                                    showNotification("安装文件共"+totalM+"M，已下载"+totalM+"M",100);
                                }
                            }
                            length=in.read(bytes);
                        }
                        //下载完毕，清除notification，安装更新文件
                        startInstallApk(new File(fileName));
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                    reTryCount++;
                    if(reTryCount< MAX_RE_TYR_COUNT){
                        //下载失败后重试
                        startDownLoadApkFile(SharedPreferencesUtil.CbbInfo.getAppLatestApkUrl(), fileName);
                    }
                }finally {
                    if(file!=null){
                        try {
                            file.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if(in!=null){
                        try {
                            in.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if(connection!=null){
                        connection.disconnect();
                    }
                }
            }
        }).start();
    }

    private static final int NOTIFY_ID=1000;
    private void showNotification(final String text,final int percent){
        handler.post(new Runnable() {
            @Override
            public void run() {
                Context context=getApplicationContext();
                NotificationManager manager=
                        (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
                Notification notification=new NotificationCompat.Builder(getApplicationContext()).
                        setLargeIcon(BitmapFactory.decodeResource(context.getResources(),
                                R.mipmap.ic_launcher)).
                        setSmallIcon(R.mipmap.ic_notify_small).
                        setColor(0xFFFFBD18).
                        setAutoCancel(false).
                        setContentTitle("更新应用").
                        setContentText(text).
                        setProgress(100,percent,false).
                        build();
                try{
                    //如果应用无发送通知权限，强行发送通知会导致应用闪退，在此做try catch处理
                    manager.notify(NOTIFY_ID,notification);
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        });
    }

    private void startInstallApk(@NonNull final File file){
        handler.post(new Runnable() {
            @Override
            public void run() {
                try{
                    //try catch处理，防止应用闪退
                    Intent intent=new Intent(Intent.ACTION_VIEW);
                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
                    startActivity(intent);
                    //退出应用
                    android.os.Process.killProcess(Process.myPid());
                    System.exit(0);
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        });
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        handler.removeCallbacksAndMessages(null);
        handler=null;
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
}
